#include "json_process.h"

int fifo_fd;
#define FIFO_PATH "/tmp/fifo"

// 全局变量
lv_obj_t *scr1 = NULL;
char location[256];
cJSON *weather_root = NULL;  // 保存天气数据的根节点

// UI控件
static lv_obj_t *current_weather_btn;
static lv_obj_t *forecast_btn;
static lv_obj_t *weather_label;
static lv_obj_t *city_label;
static lv_obj_t *return_btn;

// 样式
static lv_style_t btn_style;
static lv_style_t btn_pressed_style;
static lv_style_t label_style;

lv_font_t *font_chinese;
lv_style_t bg_style;
// 当前显示模式
typedef enum {
    SHOW_CURRENT,
    SHOW_FORECAST
} display_mode_t;

display_mode_t current_mode = SHOW_CURRENT;

/*---------各种样式初始化------------*/
/// @brief 背景色样式初始化
/// @param  lv_obj_add_style(***, &bg_style, 0);
void bg_style_init(void)
{
    lv_style_init(&bg_style);
    lv_style_set_bg_color(&bg_style, lv_palette_main(LV_PALETTE_BLUE));
    lv_style_set_bg_grad_color(&bg_style, lv_palette_main(LV_PALETTE_PURPLE));
    lv_style_set_bg_grad_dir(&bg_style, LV_GRAD_DIR_VER);
}

/// @brief 按钮样式初始化
static void btn_style_init(void)
{
    lv_style_init(&btn_style);
    lv_style_set_bg_color(&btn_style, lv_palette_main(LV_PALETTE_GREY));
    lv_style_set_bg_opa(&btn_style, LV_OPA_70);
    lv_style_set_radius(&btn_style, 10);
    lv_style_set_border_width(&btn_style, 2);
    lv_style_set_border_color(&btn_style, lv_color_white());
    
    lv_style_init(&btn_pressed_style);
    lv_style_set_bg_color(&btn_pressed_style, lv_palette_main(LV_PALETTE_BLUE));
    lv_style_set_bg_opa(&btn_pressed_style, LV_OPA_70);
}

/// @brief 标签样式初始化
static void label_style_init(void)
{
    lv_style_init(&label_style);
    lv_style_set_text_color(&label_style, lv_color_white());
    lv_style_set_text_font(&label_style, font_chinese);
    lv_style_set_text_align(&label_style, LV_TEXT_ALIGN_CENTER);
}

/// @brief 中文字体样式初始化
/// @param  lv_obj_set_style_text_font(**, font_chinese , 0);
static void chineseFontInitialization(void)
{
    static lv_ft_info_t info;
    /*FreeType uses C standard file system, so no driver letter is required.*/
    info.name = "/userdata/zjy/simhei.ttf";
    // info.name = "/zjy/simhei.ttf";
    info.weight = 20;
    info.style = FT_FONT_STYLE_NORMAL;
    info.mem = NULL;
    
    // 初始化FreeType字体
    if(!lv_ft_font_init(&info)) 
    {
        LV_LOG_ERROR("create failed.");
    }
    
    // 定义中文字体指针
    font_chinese = NULL;
    font_chinese = info.font; // 指向FreeType中的具体中文字体
}
/*--------------------------------------------------------------------------*/

/// @brief 更改url编码因为中文弄不了(ex)
/// @param str 
/// @return 
static char *url_encode(const char *str) 
{
    const char *hex = "0123456789ABCDEF";
    size_t len = strlen(str);
    char *encoded = malloc(len * 3 + 1); // 每个字符最多转3字节
    char *p = encoded;

    for (size_t i = 0; i < len; i++) {
        unsigned char c = str[i];
        if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') 
        {
            *p++ = c;
        } else 
        {
            *p++ = '%';
            *p++ = hex[c >> 4];
            *p++ = hex[c & 0x0F];
        }
    }
    *p = '\0';
    return encoded;
}

/// @brief 通过popen运行来获取bus命令的输出,过滤前面的字符获取json格式的内容
/// @param bus 
/// @return 读取到的json数据
static char *get_Json(char *bus)
{
    char *msg_buf = malloc(4096); // 增加缓冲区大小
    if (msg_buf == NULL) {
        return NULL;
    }
    FILE *fp = popen(bus, "r");
    if (fp == NULL) {
        free(msg_buf);
        return NULL;
    }
    int ret_val = fread(msg_buf, 1, 4096-1, fp);
    msg_buf[ret_val] = '\0'; // 确保字符串正确终止
    pclose(fp);
    
    // 查找JSON开始位置（在第一个{之后）
    char *json_start = strchr(msg_buf, '{');
    if (json_start == NULL) {
        free(msg_buf);
        return NULL;
    }
    
    // 提取纯JSON部分
    char *json_str = strdup(json_start);
    free(msg_buf); // 释放原始缓冲区
    
    printf("成功读取JSON：%s\n", json_str);
    return json_str;
}

/// @brief 显示当前天气信息
static void show_current_weather(void)
{
    if (weather_root == NULL) {
        lv_label_set_text(weather_label, "天气数据未加载");
        return;
    }
    
    cJSON *data = cJSON_GetObjectItem(weather_root, "data");
    if (data == NULL) {
        lv_label_set_text(weather_label, "数据格式错误");
        return;
    }
    
    cJSON *weather_data = cJSON_GetObjectItem(data, "data");
    if (weather_data == NULL || !cJSON_IsArray(weather_data)) {
        lv_label_set_text(weather_label, "天气数据格式错误");
        return;
    }
    
    // 获取今天的天气数据（数组第一个元素）
    cJSON *today = cJSON_GetArrayItem(weather_data, 0);
    if (today == NULL) {
        lv_label_set_text(weather_label, "今日天气数据不存在");
        return;
    }
    
    // 提取天气信息
    cJSON *temperature = cJSON_GetObjectItem(today, "temperature");
    cJSON *weather = cJSON_GetObjectItem(today, "weather");
    cJSON *wind = cJSON_GetObjectItem(today, "wind");
    cJSON *date = cJSON_GetObjectItem(today, "date");
    cJSON *air_quality = cJSON_GetObjectItem(today, "air_quality");
    
    // 格式化显示文本
    char buffer[512];
    snprintf(buffer, sizeof(buffer), 
             "%s\n%s\n温度: %s\n天气: %s\n风力: %s\n空气质量: %s",
             location, 
             date ? date->valuestring : "未知",
             temperature ? temperature->valuestring : "未知",
             weather ? weather->valuestring : "未知",
             wind ? wind->valuestring : "未知",
             air_quality ? air_quality->valuestring : "未知");
    
    lv_label_set_text(weather_label, buffer);
}

/// @brief 显示天气预报信息
static void show_weather_forecast(void)
{
    if (weather_root == NULL) {
        lv_label_set_text(weather_label, "天气数据未加载");
        return;
    }
    
    cJSON *data = cJSON_GetObjectItem(weather_root, "data");
    if (data == NULL) {
        lv_label_set_text(weather_label, "数据格式错误");
        return;
    }
    
    cJSON *weather_data = cJSON_GetObjectItem(data, "data");
    if (weather_data == NULL || !cJSON_IsArray(weather_data)) {
        lv_label_set_text(weather_label, "天气数据格式错误");
        return;
    }
    
    // 创建格式化字符串
    char buffer[1024];
    snprintf(buffer, sizeof(buffer), "%s\n未来天气预报:\n", location);
    
    // 遍历所有天气数据（跳过今天，从索引1开始）
    int array_size = cJSON_GetArraySize(weather_data);
    for (int i = 1; i < array_size; i++) {
        cJSON *day = cJSON_GetArrayItem(weather_data, i);
        if (day == NULL) continue;
        
        cJSON *date = cJSON_GetObjectItem(day, "date");
        cJSON *temperature = cJSON_GetObjectItem(day, "temperature");
        cJSON *weather = cJSON_GetObjectItem(day, "weather");
        
        char day_buffer[128];
        snprintf(day_buffer, sizeof(day_buffer), "%s: %s %s\n",
                 date ? date->valuestring : "未知",
                 temperature ? temperature->valuestring : "未知",
                 weather ? weather->valuestring : "未知");
        
        // 检查缓冲区是否足够
        if (strlen(buffer) + strlen(day_buffer) < sizeof(buffer)) {
            strcat(buffer, day_buffer);
        } else {
            break; // 缓冲区已满，停止添加
        }
    }
    
    lv_label_set_text(weather_label, buffer);
}



/// @brief 按钮事件处理函数
/// @param e 
static void btn_event_handler(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t *btn = lv_event_get_target(e);
    
    if (code == LV_EVENT_CLICKED) 
    {
        if (btn == current_weather_btn) 
        {
            current_mode = SHOW_CURRENT;
            show_current_weather();
        } 
        else if (btn == forecast_btn) 
        {
            current_mode = SHOW_FORECAST;
            show_weather_forecast();
        }
        else if (btn = return_btn)
        {
            //返回主界面
            lv_scr_load(scr_main);
        }
    }
}

/// @brief 获得的天气预报数据处理
void jsonDataProcessing(void)
{
    char *ip_msg = get_Json("curl -k \"https://apis.juhe.cn/iplocation/ipv4dist/query?key=26c1e13a3e11de9b2269ee4c6c7fb5a8&ip=113.66.99.51\""); // 现在返回纯JSON内容
    if (ip_msg == NULL) {
        printf("获取JSON失败\n");
        return;
    }
    
    cJSON *root = cJSON_Parse(ip_msg);
    if (root == NULL) {
        const char *error_ptr = cJSON_GetErrorPtr();
        if (error_ptr != NULL) {
            printf("解析JSON错误位置: %s\n", error_ptr);
        }
        printf("解析JSON失败，原始内容: %s\n", ip_msg);
        free(ip_msg);
        return;
    }
    
    cJSON *errCode = cJSON_GetObjectItem(root, "error_code");
    if (errCode == NULL) 
    {
        printf("没有找到error_code字段\n");
        cJSON_Delete(root);
        free(ip_msg);
        return;
    }
    
    cJSON *result = cJSON_GetObjectItem(root, "result");
    if (result == NULL) {
        printf("没有找到result字段\n");
        cJSON_Delete(root);
        free(ip_msg);
        return;
    }
    
    cJSON *city = cJSON_GetObjectItem(result, "city");
    cJSON *district = cJSON_GetObjectItem(result, "district");

    // 修复：根据实际API响应，error_code为0表示成功，不是200
    if (errCode->valueint == 0)
    {
        printf("请求成功\n");
        
        if (city && district && cJSON_IsString(city) && cJSON_IsString(district))
        {
            snprintf(location, sizeof(location), "%s%s", city->valuestring, district->valuestring);
            printf("位置: %s\n", location);
            
            // 更新城市标签
            if (city_label) {
                lv_label_set_text(city_label, location);
            }
        }
        else
        {
            printf("无法获取位置信息\n");
            strcpy(location, "未知地区");
        }
    }
    else
    {
        printf("请求失败，错误码: %d\n", errCode->valueint);
        strcpy(location, "未知地区");
    }
    
    // 用上一个api获取的本地所属地来获取天气
    char *encoded_city = url_encode(location);
    char bus[512];
    snprintf(bus, sizeof(bus), "curl -k \"https://v2.api-m.com/api/weather?city=%s\"", encoded_city);
    char *weather_msg = get_Json(bus);
    free(encoded_city);
    
    if (weather_msg) {
        // 释放之前的天气数据
        if (weather_root) {
            cJSON_Delete(weather_root);
            weather_root = NULL;
        }
        
        // 解析新的天气数据
        weather_root = cJSON_Parse(weather_msg);
        free(weather_msg);
        
        if (weather_root) {
            // 根据当前显示模式更新天气信息
            if (current_mode == SHOW_CURRENT) 
            {
                show_current_weather();
            } else {
                show_weather_forecast();
            }
        } 
        else 
        {
            printf("解析天气数据失败\n");
            if (weather_label) 
            {
                lv_label_set_text(weather_label, "解析天气数据失败");
            }
        }
    } else 
    {
        printf("获取天气数据失败\n");
        if (weather_label) 
        {
            lv_label_set_text(weather_label, "获取天气数据失败");
        }
    }
    
    // 释放内存
    cJSON_Delete(root);
    free(ip_msg);
}

void ui(void)
{
    bg_style_init();
    chineseFontInitialization();
    btn_style_init();
    label_style_init();
    
    scr1 = lv_obj_create(NULL);
    lv_obj_add_style(scr1, &bg_style, 0);
    lv_obj_clear_flag(scr1, LV_OBJ_FLAG_SCROLLABLE);
    lv_scr_load(scr1); 
    
    // 创建城市标签
    city_label = lv_label_create(scr1);
    lv_obj_add_style(city_label, &label_style, 0);
    lv_label_set_text(city_label, location);
    lv_obj_align(city_label, LV_ALIGN_TOP_MID, 0, 20);
    
    // 创建天气信息标签
    weather_label = lv_label_create(scr1);
    lv_obj_add_style(weather_label, &label_style, 0);
    lv_label_set_text(weather_label, "正在加载天气数据...");
    lv_obj_set_size(weather_label, 800, 400);
    lv_obj_align(weather_label, LV_ALIGN_CENTER, 0, 0);
    lv_label_set_long_mode(weather_label, LV_LABEL_LONG_WRAP);
    
    // 创建当前天气按钮
    current_weather_btn = lv_btn_create(scr1);
    lv_obj_add_style(current_weather_btn, &btn_style, 0);
    lv_obj_add_style(current_weather_btn, &btn_pressed_style, LV_STATE_PRESSED);
    lv_obj_set_size(current_weather_btn, 150, 50);
    lv_obj_align(current_weather_btn, LV_ALIGN_BOTTOM_LEFT, 50, -30);
    lv_obj_add_event_cb(current_weather_btn, btn_event_handler, LV_EVENT_ALL, NULL);
    
    lv_obj_t *current_label = lv_label_create(current_weather_btn);
    lv_label_set_text(current_label, "当前天气");
    lv_obj_center(current_label);
    lv_obj_set_style_text_font(current_label, font_chinese, 0);
    
    // 创建天气预报按钮
    forecast_btn = lv_btn_create(scr1);
    lv_obj_add_style(forecast_btn, &btn_style, 0);
    lv_obj_add_style(forecast_btn, &btn_pressed_style, LV_STATE_PRESSED);
    lv_obj_set_size(forecast_btn, 150, 50);
    // lv_obj_align(forecast_btn, LV_ALIGN_BOTTOM_RIGHT, -50, -30);
    lv_obj_align_to(forecast_btn,current_weather_btn,LV_ALIGN_OUT_RIGHT_MID,20,0);
    lv_obj_add_event_cb(forecast_btn, btn_event_handler, LV_EVENT_ALL, NULL);
    
    lv_obj_t *forecast_label = lv_label_create(forecast_btn);
    lv_label_set_text(forecast_label, "天气预报");
    lv_obj_center(forecast_label);
    lv_obj_set_style_text_font(forecast_label, font_chinese, 0);

    // 创建天气预报按钮
    return_btn = lv_btn_create(scr1);
    lv_obj_add_style(return_btn, &btn_style, 0);
    lv_obj_add_style(return_btn, &btn_pressed_style, LV_STATE_PRESSED);
    lv_obj_set_size(return_btn, 150, 50);
    // lv_obj_align(return_btn, LV_ALIGN_BOTTOM_RIGHT, 0, 0);
    lv_obj_align_to(return_btn,forecast_btn,LV_ALIGN_OUT_RIGHT_MID,20,0);
    lv_obj_add_event_cb(return_btn, btn_event_handler, LV_EVENT_ALL, NULL);
    
    lv_obj_t *return_label = lv_label_create(return_btn);
    lv_label_set_text(return_label, "返回界面");
    lv_obj_center(return_label);
    lv_obj_set_style_text_font(return_label, font_chinese, 0);

}